package.cpath = "./skynet/luaclib/?.so;".. package.cpath
package.path = "./skynet/lualib/?.lua;./app/common/lib/?.lua;./testclient/?.lua;" .. package.path

if _VERSION ~= "Lua 5.3" then
	error "Use lua 5.3"
end

local socket = require "client.websocket"
local protobuf = require "protobuf"
local parser = require "parser"

parser.register("./app/proto/primary.proto")
parser.register("./app/proto/gone.proto")

local decode = require "protopack"

-- local fd = assert(socket.connect("192.168.6.202", 8889))
local fd = assert(socket.connect("127.0.0.1", 8890))
-- local fd = assert(socket.connect("192.168.6.81", 8890))

local function send_package(fd, pack)
	-- 使用了websocket ，会自己组织帧格式的
	socket.send(fd, pack)
end

local function recv_package()
	local r , istimeout= socket.recv(fd, 100)
	if not r then
		return nil
	end
	if r == ""  and (not istimeout ) then
		error "Server closed"
	end
	return r
end


local function send_request(msgname, msg)
	print(msgname)
	print(msg)
	local str = decode.c2spack(protobuf, msgname, msg)
	send_package(fd, str)
end

local last = ""

local function print_request(name, args)
	print("REQUEST", name)
	if args then
		for k,v in pairs(args) do
			print(k,v)
		end
	end
end

local function print_response(msghead, msgbody)
	print('------ begin response --------')
	if msghead then
		for k,v in pairs(msghead) do
			print(k,v)
		end
	end
	if msgbody then
		for k,v in pairs(msgbody) do
			print(k,v)
			if type(v) == "table" then
				print("-- table: ", k )
				for i,j in pairs(v) do
					print("  --", i,j)
				end
			end
		end
	end
	print('------ end response --------')
end

local function dispatch_package()
	while true do
		local v
		v = recv_package()
		if not v  or v == "" then
			break
		end
		print_response(decode.s2cunpack(protobuf, v))
	end
end
-- send_request("login", {uid=1234, logintoken='46634e1c0013cdea0172e1fab15bc94b1504418301'})
send_request("entergame", {rid=12, uid=1234,expiretime=0, gatetoken='46634e1c0013cdea0172e1fab15bc94b1504418301'})

-- socket.usleep(2000)
-- send_request("intogame", 1, { rid = 1 })
while true do
	dispatch_package()
	local cmd = socket.readstdin()
	if cmd then
		if cmd == "hi" then
			send_request("hi", {test='rolenameabc'})
		elseif cmd == "heart" then
			send_request("heart", {})
		elseif cmd == "get" then
			send_request("getroleinfo", {})
		elseif cmd == "hello" then
			send_request("hello", {test='rolenameabc'})
		elseif cmd == "tab" then
			send_request("gone.tab", 123, {key='getkeyabc'})
		elseif cmd == "quitgame" then
			send_request("quitgame", {}, 1)
		end
	else
		socket.usleep(100)
	end
end
